package common

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/nacos-group/nacos-sdk-go/v2/inner/uuid"
	"go.uber.org/zap"
	"hosptial-record/global"
	"hosptial-record/global/response"
	"hosptial-record/utils/picture"
	"net/http"
	"os"
	"path/filepath"
	"time"
)

func UploadFile(ctx *gin.Context) {
	form, err := ctx.MultipartForm()
	files := form.File["file"]
	if err != nil {
		zap.S().Errorf("[UploadFile] 获取文件失败:%s", err)
		ctx.JSON(http.StatusBadRequest, response.BaseResponse{
			Msg: "文件格式有问题",
		})
	}
	// 获取当前时间年月日
	year, month, day := time.Now().Date()
	cTime := fmt.Sprintf("%d-%d-%d", year, month, day)
	picturePath := filepath.Join(global.ServerConfig.FilePath, "picture", cTime)
	imgs := make([]string, 0)
	for _, file := range files {
		uuid, _ := uuid.NewV4()
		filename := uuid.String() + file.Filename
		path := filepath.Join(picturePath, filename)
		err := ctx.SaveUploadedFile(file, path)
		if err != nil {
			zap.S().Errorw("Common [UploadFile] 保存文件失败:", "msg", err)
			ctx.JSON(http.StatusInternalServerError, response.BaseResponse{
				Msg:  "保存文件失败",
				Data: err,
			})
			return
		}
		// 图片压缩
		dir, _ := os.Getwd()
		inputPath := filepath.Join(dir, global.ServerConfig.FilePath, "picture", cTime, filename)
		err = picture.CompressImage(inputPath, inputPath, 60)
		if err != nil {
			zap.S().Errorw("Common [UploadFile] 图片压缩失败:", "msg", err)
			ctx.JSON(http.StatusInternalServerError, response.BaseResponse{
				Msg:  "图片压缩失败",
				Data: err,
			})
			return
		}
		imgs = append(imgs, path)
	}
	ctx.JSON(http.StatusOK, response.BaseResponse{
		Msg:  "上传成功",
		Data: imgs,
	})
}
